package com.hethongviet.job.helpers.database;

import java.util.ArrayList;
import java.util.List;

import com.hethongviet.job.AppMain;
import com.hethongviet.job.models.User;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class LoginInfoSQLite
{
	public static final String TABLE_NAME = "logininfos";
	public static final String COLUMN_ID_DB = "_id";
	public static final String COLUMN_USERNAME = "username";
	public static final String COLUMN_PASSWORD = "password";
	public static final String COLUMN_ACTIVATION_CODE = "activationcode";
	public static final String COLUMN_AUTO_LOGIN = "autologin";
	public static final String COLUMN_DOMAIN = "domain";

	public static final String COLUMN_SETTING_SCALE_IMAGE = "scale_image";

	// Database fields
	private SQLiteDatabase _database;
	private MySQLiteHelper _dbHelper;
	private String[] allColumns = { COLUMN_ID_DB, COLUMN_USERNAME,
			COLUMN_PASSWORD, COLUMN_ACTIVATION_CODE, COLUMN_AUTO_LOGIN,
			COLUMN_SETTING_SCALE_IMAGE, COLUMN_DOMAIN };

	public static final String STRING_COLUMNS = COLUMN_ID_DB
			+ " integer primary key autoincrement, " + COLUMN_USERNAME
			+ " text not null, " + COLUMN_PASSWORD + " text not null, "
			+ COLUMN_ACTIVATION_CODE + " text not null, " + COLUMN_AUTO_LOGIN
			+ " integer not null, " + COLUMN_SETTING_SCALE_IMAGE
			+ " integer not null, " + COLUMN_DOMAIN + " text not null";

	public LoginInfoSQLite(Context context)
	{
		List<String> tableNames = new ArrayList<String>();
		List<String> tableColumns = new ArrayList<String>();

		tableNames.add(TABLE_NAME);
		tableNames.add(ProjectSQLite.TABLE_NAME);
		tableNames.add(TaskSQLite.TABLE_NAME);
		tableNames.add(CommentSQLite.TABLE_NAME);

		tableColumns.add(STRING_COLUMNS);
		tableColumns.add(ProjectSQLite.STRING_COLUMNS);
		tableColumns.add(TaskSQLite.STRING_COLUMNS);
		tableColumns.add(CommentSQLite.STRING_COLUMNS);

		_dbHelper = new MySQLiteHelper(context, tableNames, tableColumns);
	}

	public void open() throws SQLException
	{
		_database = _dbHelper.getWritableDatabase();
	}

	public void close()
	{
		_dbHelper.close();
	}

	// public User createUser(String userName, String ac, String password,
	// boolean isAutoLogin, boolean isRemember)
	// {
	// ContentValues values = new ContentValues();
	// values.put(COLUMN_USERNAME, userName);
	// values.put(COLUMN_PASSWORD, password);
	// values.put(COLUMN_ACTIVATION_CODE, password);
	// values.put(COLUMN_AUTO_LOGIN, isAutoLogin ? 1 : 0);
	// values.put(COLUMN_REMEMBER, isRemember ? 1 : 0);
	// long insertId = _database.insert(TABLE_LOGIN, null, values);
	// Cursor cursor = _database.query(TABLE_LOGIN, allColumns, COLUMN_ID
	// + " = " + insertId, null, null, null, null);
	// cursor.moveToFirst();
	// User user = cursorToUser(cursor);
	// cursor.close();
	// return user;
	// }
	//

	public void insertOneUser(User user)
	{
		open();
		AppMain.debug("insert one user-- " + user.getUsername());

		deleteAll();

		open();

		AppMain.debug("insert -- " + user.getUsername() + "   remember");

		ContentValues values = new ContentValues();

		values.put(COLUMN_USERNAME, user.getUsername());
		values.put(COLUMN_PASSWORD, user.getPassword());
		values.put(COLUMN_ACTIVATION_CODE, user.getActivationCode());
		values.put(COLUMN_AUTO_LOGIN, user.isAutoLogin() ? 1 : 0);
		values.put(COLUMN_SETTING_SCALE_IMAGE,
				user.isSettingScaleImage() ? 1 : 0);
		values.put(COLUMN_DOMAIN, user.getDomain());

		_database.insert(TABLE_NAME, null, values);

		close();
	}

	public void insertUser(User user)
	{
		open();
		AppMain.debug("insert -- " + user.getUsername());
		Cursor cursor = _database.query(TABLE_NAME, allColumns, null, null,
				null, null, null);
		cursor.moveToFirst();
		// if (!user.isAutoLogin())
		// {
		// //
		// AppMain.debug("insert -- " + user.getUsername() + "   no remember");
		// if (!cursor.isAfterLast())
		// {
		// deleteUser(cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB)));
		// open();
		// }
		// }
		// else
		{
			AppMain.debug("insert -- " + user.getUsername() + "   remember");
			ContentValues values = new ContentValues();

			values.put(COLUMN_USERNAME, user.getUsername());
			values.put(COLUMN_PASSWORD, user.getPassword());
			values.put(COLUMN_ACTIVATION_CODE, user.getActivationCode());
			values.put(COLUMN_AUTO_LOGIN, user.isAutoLogin() ? 1 : 0);
			values.put(COLUMN_SETTING_SCALE_IMAGE,
					user.isSettingScaleImage() ? 1 : 0);
			values.put(COLUMN_DOMAIN, user.getDomain());

			if (!cursor.isAfterLast())
			{
				Long id = cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB));
				String activationCode = cursor.getString(cursor.getColumnIndex(COLUMN_ACTIVATION_CODE));
				String username = cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME));
				String password = cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD));
				String domain = cursor.getString(cursor.getColumnIndex(COLUMN_DOMAIN));
				boolean isAutoLogin = cursor.getLong(cursor.getColumnIndex(COLUMN_AUTO_LOGIN)) == 1;

				if (!username.equalsIgnoreCase(user.getUsername())
						|| !activationCode.equalsIgnoreCase(user.getActivationCode()))
				{
					AppMain.debug("insert 1111111111111 new");
					/* Delete old */
					deleteUser(id);
					open();
					/* Insert new */
					_database.insert(TABLE_NAME, null, values);

				}
				else if (!password.equals(user.getPassword())
						|| (isAutoLogin != user.isAutoLogin())
						|| !domain.equals(user.getDomain()))
				{
					AppMain.debug("insert 1111111111111 update");
					/* Update to database */
					_database.update(TABLE_NAME, values, COLUMN_ID_DB + "="
							+ id, null);
				}
			}
			else
			{
				/* Insert new */
				AppMain.debug("insert 1111111111111 insert new");
				_database.insert(TABLE_NAME, null, values);

				// _database.rawQuery(
				// "insert into " + TABLE_LOGIN + "(" + COLUMN_USERNAME + ", "
				// + COLUMN_PASSWORD + ", " + COLUMN_ACTIVATION_CODE
				// + ", " + COLUMN_AUTO_LOGIN + ", " + COLUMN_REMEMBER
				// + ") values(" + user.getUsername() + ", "
				// + user.getPassword() + ", "
				// + user.getActivationCode() + ", "
				// + (user.isAutoLogin() ? 1 : 0) + ", "
				// + (user.isRemember() ? 1 : 0) + ")", null);
			}
		}
		cursor.close();
		close();
	}

	public void insertUserRaw(User user)
	{
		open();

		AppMain.debug("insert -- " + user.getUsername());

		Cursor cursor = _database.query(TABLE_NAME, allColumns, null, null,
				null, null, null);

		cursor.moveToFirst();

		// if (!user.isAutoLogin())
		// {
		// AppMain.debug("insert -- " + user.getUsername() + "   no remember");
		// if (!cursor.isAfterLast())
		// {
		// deleteUser(cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB)));
		// }
		// }
		// else
		{
			AppMain.debug("insert -- " + user.getUsername() + "   remember");

			if (!cursor.isAfterLast())
			{
				Long id = cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB));
				String activationCode = cursor.getString(cursor.getColumnIndex(COLUMN_ACTIVATION_CODE));
				String username = cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME));
				String password = cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD));
				String domain = cursor.getString(cursor.getColumnIndex(COLUMN_DOMAIN));
				boolean isAutoLogin = cursor.getLong(cursor.getColumnIndex(COLUMN_AUTO_LOGIN)) == 1;

				if (!username.equalsIgnoreCase(user.getUsername())
						|| !activationCode.equalsIgnoreCase(user.getActivationCode())
						|| !domain.equals(user.getDomain()))
				{
					AppMain.debug("insert 1111111111111 new");
					/* Delete old */
					deleteUser(id);
					/* Insert new */
					_database.rawQuery(
							"INSERT " + TABLE_NAME + "(" + COLUMN_USERNAME
									+ ", " + COLUMN_PASSWORD + ", "
									+ COLUMN_ACTIVATION_CODE + ", "
									+ COLUMN_DOMAIN + ", " + COLUMN_AUTO_LOGIN
									+ ", " + COLUMN_SETTING_SCALE_IMAGE
									+ ") values( " + user.getUsername() + ", "
									+ user.getPassword() + ", "
									+ user.getActivationCode() + ", "
									+ user.getDomain() + ", "
									+ (user.isAutoLogin() ? 1 : 0) + ", "
									+ (user.isSettingScaleImage() ? 1 : 0)
									+ ")", null);

				}
				else if (!password.equals(user.getPassword())
						|| (isAutoLogin != user.isAutoLogin()))
				{
					AppMain.debug("insert 1111111111111 update");
					/* Update to database */
					_database.rawQuery(
							"UPDATE " + TABLE_NAME + " SET " + COLUMN_USERNAME
									+ " = " + user.getUsername() + ","
									+ COLUMN_PASSWORD + " = "
									+ user.getPassword() + ", "
									+ COLUMN_ACTIVATION_CODE + " = "
									+ user.getActivationCode() + ", "
									+ COLUMN_AUTO_LOGIN + " = "
									+ (user.isAutoLogin() ? 1 : 0) + ", "
									+ COLUMN_SETTING_SCALE_IMAGE + " = "
									+ (user.isSettingScaleImage() ? 1 : 0)
									+ ", " + " WHERE " + COLUMN_ID_DB + " = "
									+ user.getIdDB(), null);

				}
			}
			else
			{
				/* Insert new */
				AppMain.debug("insert 1111111111111 insert new");
				_database.rawQuery(
						"INSERT " + TABLE_NAME + "(" + COLUMN_USERNAME + ", "
								+ COLUMN_PASSWORD + ", "
								+ COLUMN_ACTIVATION_CODE + ", " + COLUMN_DOMAIN
								+ ", " + COLUMN_AUTO_LOGIN + ", "
								+ COLUMN_SETTING_SCALE_IMAGE + ") values( "
								+ user.getUsername() + ", "
								+ user.getPassword() + ", "
								+ user.getActivationCode() + ", "
								+ user.getDomain() + ", "
								+ (user.isAutoLogin() ? 1 : 0)
								+ (user.isSettingScaleImage() ? 1 : 0) + ")",
						null);
			}
		}
		cursor.close();
		close();
	}

	public void updateSetting(User user)
	{
		open();

		AppMain.debug("1111111111111 update setting!");

		/* Update to database */

		ContentValues contentValues = new ContentValues();
		contentValues.put(COLUMN_SETTING_SCALE_IMAGE,
				(user.isSettingScaleImage() ? "1" : "0"));
		_database.update(TABLE_NAME, contentValues, COLUMN_USERNAME + " = \'"
				+ user.getUsername() + "\'", null);

		close();
	}

	public User getUser()
	{
		open();
		Cursor cursor = _database.query(TABLE_NAME, allColumns, null, null,
				null, null, null);
		cursor.moveToFirst();
		User user = null;
		if (!cursor.isAfterLast())
		{
			user = cursorToUser(cursor);
		}
		// Make sure to close the cursor
		cursor.close();
		close();
		return user;
	}

	public void deleteAll()
	{
		open();

		System.out.println("user deleted all");

		_database.delete(TABLE_NAME, "1", null);

		close();
	}

	public void deleteUser(User user)
	{
		open();
		System.out.println("Comment deleted with id: " + user.getIdDB());
		_database.rawQuery("DELETE FROM " + TABLE_NAME + " WHERE "
				+ COLUMN_ID_DB + " = " + user.getIdDB(), null);
		close();
	}

	public void deleteUser(long id)
	{
		open();
		System.out.println("Comment deleted with id: " + id);
		_database.rawQuery("DELETE FROM " + TABLE_NAME + " WHERE "
				+ COLUMN_ID_DB + " = " + id, null);
		close();
	}

	public List<User> getAllUsers()
	{
		open();
		List<User> listUsers = new ArrayList<User>();

		Cursor cursor = _database.query(TABLE_NAME, allColumns, null, null,
				null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast())
		{
			User user = cursorToUser(cursor);
			listUsers.add(user);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		close();
		return listUsers;
	}

	private User cursorToUser(Cursor cursor)
	{
		User user = new User();
		user.setUsername(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
		user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD)));
		user.setActivationCode(cursor.getString(cursor.getColumnIndex(COLUMN_ACTIVATION_CODE)));
		user.setAutoLogin(cursor.getLong(cursor.getColumnIndex(COLUMN_AUTO_LOGIN)) == 1);
		user.setSettingScaleImage(cursor.getLong(cursor.getColumnIndex(COLUMN_SETTING_SCALE_IMAGE)) == 1);
		user.setDomain(cursor.getString(cursor.getColumnIndex(COLUMN_DOMAIN)));
		return user;
	}
}
